package com.minutes.in.seconds.ui.screens;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import com.minutes.in.seconds.R;
import com.minutes.in.seconds.common.BitmapHandler;
import com.minutes.in.seconds.common.Constants;
import com.minutes.in.seconds.ui.event.AddContactEventHandler;

public class AddContactActivity extends Activity {

	private AddContactEventHandler eventHandler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_contacts);
		this.setupClickListeners();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	private void setupClickListeners() {
		this.eventHandler = new AddContactEventHandler(this.findViewById(R.id.add_contacts_wrapper));
		this.findViewById(R.id.profile_photo).setOnClickListener(this.eventHandler);
		this.findViewById(R.id.add_contact).setOnClickListener(this.eventHandler);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case Constants.PICK_PHOTO_FLAG:
			if (resultCode == RESULT_OK) {
				ProgressDialog progress = new ProgressDialog(this);
				progress.setMessage(getString(R.string.wait_message));
				progress.setCancelable(false);
				progress.show();
				Uri _uri = data.getData();

				// User had pick an image.
				Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
				cursor.moveToFirst();

				// Link to the image
				final String imageFilePath = cursor.getString(0);
				cursor.close();

				// Creating bitmap of the selected image from its inputstream
				Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath);
				Bitmap circularBitmap = BitmapFactory.decodeFile(imageFilePath);

				// Getting reference to ImageView
				ImageView profilePhoto = (ImageView) findViewById(R.id.profile_photo);

				if (Constants.profileImageSize == null) {
					Constants.profileImageSize = ((BitmapDrawable) profilePhoto.getDrawable()).getBitmap().getWidth();
				}

				circularBitmap = BitmapHandler.getCroppedBitmap(circularBitmap, Constants.profileImageSize);

				// Setting Bitmap to ImageButton
				profilePhoto.setImageBitmap(circularBitmap);
				this.eventHandler.setBitmap(bitmap);
				progress.dismiss();
			}
		}
	}
}